package com.yuncheng.oaApi.controller;

import com.yuncheng.oaApi.vo.OaFlowVo;
import com.yuncheng.oaApi.vo.OaGwycVo;
import com.yuncheng.oaApi.vo.Result;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaLogConstant;
import com.yuncheng.oaApi.constant.OaGwycOaFlowConstants;
import com.yuncheng.oaApi.entity.OaGwyc;

import com.yuncheng.oaApi.entity.OaJobEntity;
import com.yuncheng.oaApi.lcService.OaGwycOaFlowService;
import com.yuncheng.oaApi.mapper.OaGwycFlowMapper;
import com.yuncheng.oaApi.service.IOaGwycService;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.oaApi.service.IOaSpcySqsxJobService;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.oaApi.utils.GetUuIdUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "OA-公务用车申请接口")
@RestController
@RequestMapping("/api/spzx-oa/flow-gwyc")
public class OaGwycFlowController {

    private static final Logger log = LoggerFactory.getLogger(OaGwycFlowController.class);
    @Resource
    private OaGwycOaFlowConstants oaGwycFlowConstant;

    @Resource
    private OaGwycFlowMapper oaGwycFlowMapper;

    @Resource
    private OaGwycOaFlowService oaGwycFlowService;

    @Resource
    private IOaGwycService oaGwycService;

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    private ISpcyLogService spcyLogService;

    /**
     * 流程列表分页查询
     * @param oaGwycVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(
            OaGwycVo oaGwycVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser){
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaGwycVo> page = new Page<>(pageNo, pageSize);
        oaGwycVo.setFlcmc(oaGwycFlowConstant.getFlowName());
        IPage<OaGwycVo> list = oaGwycFlowMapper.flowJkPage(page,onlyCurrentUser,user,oaGwycVo);
        return HttpResult.ok(list);
    }

    /**
     * 流程列表分页查询
     * @param oaGwycVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程列表-分页查询")
    @ApiOperation(value = "流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(
            OaGwycVo oaGwycVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser){
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaGwycVo> page = new Page<>(pageNo, pageSize);
        oaGwycVo.setFlcmc(oaGwycFlowConstant.getFlowName());
        IPage<OaGwycVo> list = oaGwycFlowMapper.flowJobPage(page,onlyCurrentUser,user,oaGwycVo);
        return HttpResult.ok(list);
    }


    @AutoLog(value = "发起公务用车申请流程")
    @ApiOperation(value = "发起公务用车申请流程")
    @PostMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestBody OaGwyc oaGwyc){
        String oaid="";
        //当前人的id
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        if (StringUtils.isNotBlank(oaGwyc.getId())){
            OaGwyc oaids = oaGwycService.getById(oaGwyc.getId());
              oaid = oaGwyc.getId();
//
//            oaids.setFldsp(oaGwyc.getFldsp()); //领导审批
//            oaids.setFuserid(oaGwyc.getFuserid()); //用户ID
//            oaids.setFsffqlc(oaGwyc.getFsffqlc()); //是否发起流程
//            oaids.setFlczt(oaGwyc.getFlczt()); //流程状态

            ConvertUtils.register(new DateConvert(), java.util.Date.class);
            try {
                BeanUtils.populate(oaids,BeanUtils.describe(oaGwyc));
            } catch (IllegalAccessException e) {
                log.error("出错-保存事项【非法访问异常】,{}",e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("出错-保存事项【调用TargetException】,{}",e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("出错-找不到可用方法",e.getMessage());
            }

            oaGwycService.updateById(oaids);
        }else {
            oaid = GetUuIdUtils.ReplaceUuId();
            oaGwyc.setId(oaid);
            oaGwyc.setFycbm(currentUser.getDeptName());
            oaGwyc.setFuserid(currentUser.getId());

            oaGwycService.save(oaGwyc);
        }

        /**
         * @Author: lhb
         * @Description : 是否发起流程   如果是开始申请就跳转流程
         *               在这里设置 nextNodeName 指定下个环节节点 做当前跳转流程的判断，然后设置变量接收环节的值，写到nextNodeName中
         * @DateTime:
         * @Params: Fsffqlc
         */
        String msg = "保存成功";
        // 初始化流程
        Result result = oaGwycFlowService.initJob(oaid, currentUser);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }else {
            OaJobEntity job = (OaJobEntity)result.getResult();
            if (job != null) {
                // 是否提交流程
                if (StringUtils.isNotBlank(oaGwyc.getFsffqlc()) && oaGwyc.getFsffqlc().equals("是")) {
                    Result result1 = oaGwycFlowService.passJob(oaid, job.getId(), "同意", "", "");
                    if (!result1.isSuccess()) {
                        return HttpResult.error(result.getMessage());
                    }
                    msg = "提交成功";
                }
            }
        }
        HttpResult http = new HttpResult(true);
        http.setMessage(msg);
        http.setResult(oaGwyc);
        return http;
    }


    /**
     * 离岗流程保存接口
     */
    @AutoLog(value = "公务用车申请流程保存接口")
    @ApiOperation(value = "公务用车申请流程保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SAVE; // 保存
        String jobId = oaFlowVo.getJobid(); // 当前流程任务id
        String oaid = oaFlowVo.getOaid(); // 当前办公主键id
        String opinion = oaFlowVo.getOpinion(); // 办理意见

        if (StringUtils.isBlank(oaid)){
            return HttpResult.error("办公主键id参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }

        // 流程处理
        Result httpResult = oaGwycFlowService.handleFlow(oaFlowVo, null, jobId, oaid, submitType, opinion);
        if (!httpResult.isSuccess()){
            return HttpResult.error(httpResult.getMessage());
        }

        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");

        res.setResult(map);
        return res;
    }

    /**
     * 公务用车申请流程提交接口
     */
    @AutoLog(value = "公务用车申请流程提交接口")
    @ApiOperation(value = "公务用车申请流程提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = oaFlowVo.getJobid();
        String oaid = oaFlowVo.getOaid();
        String opinion = oaFlowVo.getOpinion();
        if (StringUtils.isBlank(oaid)){
            return HttpResult.error("办公主键id参数丢失，请联系管理员");
        }

        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }



       /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/

        OaJobEntity nowJob = null;

        Result httpResult1 = oaGwycFlowService.handleFlow(oaFlowVo, nowJob, jobId, oaid, submitType, opinion);
        if (!httpResult1.isSuccess()){
            return HttpResult.error(httpResult1.getMessage());
        }

        return HttpResult.ok("提交成功");
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @AutoLog(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid",name = "流程任务id",required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid")String jobid){
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = oaGwycFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }


    /**
     * 退回上一环节流程任务
     */
    @AutoLog(value = "退回上一环节流程任务")
    @ApiOperation(value = "退回上一环节流程任务")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid",value = "流程任务id",required = true),
            @ApiImplicitParam(name = "opinion",value = "意见",required = true)
    })
    @PostMapping(value = "returnUpperFlowJob")
    public HttpResult<?> returnUpperFlowJob(@RequestBody Map map){
        String jobid = map.get("jobid").toString();
        String opinion = map.get("opinion").toString();
        Result result = oaGwycFlowService.getReturnUpperFlowJob(jobid,opinion);
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok("退回成功");
    }

    @AutoLog(value = "删除公务用车请示流程")
    @ApiOperation(value = "删除公务用车请示流程")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobids",value = "流程任务id,逗号分割",required = true)
    })
    @DeleteMapping(value = "deleteGwycFlowJob")
    public HttpResult<?> deleteGwycFlowJob(@RequestParam("jobids")String jobids){
        if (StringUtils.isBlank(jobids)){
            return HttpResult.error("参数不能为空");
        }
        List<String> jobIdList = Arrays.asList(jobids.split(","));
        String logNr = "";
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(jobIdList)){
            List<OaJobEntity> jobList = spcySqsxJobService.listByIds(jobIdList);
            if (CollectionUtils.isNotEmpty(jobList)){
                for (OaJobEntity job : jobList) {
                    spcySqsxJobService.removeById(job.getId());
                    OaGwyc oaGwyc = oaGwycService.getById(job.getFpid());
                    if (oaGwyc != null) {
                        oaGwycService.removeById(job.getFpid());

                        logNr = "删除离岗请示" + job.getFhjmc() + ": ";
                        map = ObjectToMapUtils.objectToMap(oaGwyc);
                        logNr += LogUtils.MapToStringMethod(map);

                        spcyLogService.addLogs(job.getFhjmc(), logNr, job.getFpid(), OaLogConstant.LOGS_OA_GWYC, OaCommonFlowConstant.LOGS_SYS_TYPE_SC);
                    }
                }
            }
        }

        return HttpResult.ok("删除成功");
    }

}
